package com.tarena.lbs.user.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.user.dao.mapper.UserGroupMapper;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class UserGroupRepositoryImpl implements UserGroupRepository {
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Override
    public void saveUserGroup(UserGroupPO userGroupPO) {
        log.debug("保存人群数据业务处理,入参:{}",userGroupPO);
        // 判断是新增还是修改
        if (userGroupPO.getId() == null) {
            userGroupMapper.insert(userGroupPO);
        }else {
            userGroupMapper.updateById(userGroupPO);
        }
    }

    @Override
    public PageInfo<UserGroupPO> userGroupList(UserGroupQuery query) {
        QueryWrapper<UserGroupPO> queryWrapper = assembleUserQuery(query);
        //PageHelper.startPage 之间不能有代码
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<UserGroupPO> pos = userGroupMapper.selectList(queryWrapper);
        //selectList 数据库操作 之间不能有代码
        return new PageInfo<>(pos);
    }

    private QueryWrapper<UserGroupPO> assembleUserQuery(UserGroupQuery query) {
        QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();
        //1.group_name 用户群组名 模糊查询 非空 where group_name like(%#{}%)
        if (StringUtils.isNotBlank(query.getGroupName())) {
            queryWrapper.like("group_name",query.getGroupName());
        }
        return queryWrapper;
    }

    @Override
    public UserGroupPO getUserGroupById(Long id) {
        return userGroupMapper.selectById(id);
    }

    /**
     * 根据标签ID列表和商家ID查找匹配的用户组ID
     * 这个方法模拟了lbs-basic模块中UserGroupMapper.xml定义的SQL查询逻辑
     * @param tagIds 标签ID列表
     * @param businessId 商家ID
     * @return 匹配的用户组ID列表
     */
    @Override
    public List<Integer> findUserGroupIdsByTagIdsAndBizId(List<Integer> tagIds, Integer businessId) {
        QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();

        // 添加商家ID条件
        if (businessId != null) {
            queryWrapper.eq("business_id", businessId);
        }

        // 添加标签条件 - 查找包含任意一个标签的用户组
        if (tagIds != null && !tagIds.isEmpty()) {
            if (businessId != null) {
                // 当businessId不为空时，需要将标签条件用括号括起来
                queryWrapper.and(wrapper -> {
                    for (int i = 0; i < tagIds.size(); i++) {
                        if (i > 0) {
                            wrapper.or();
                        }
                        wrapper.apply("FIND_IN_SET({0}, tag_ids)", tagIds.get(i));
                    }
                });
            } else {
                // 当businessId为空时，直接添加标签条件
                for (int i = 0; i < tagIds.size(); i++) {
                    if (i > 0) {
                        queryWrapper.or();
                    }
                    queryWrapper.apply("FIND_IN_SET({0}, tag_ids)", tagIds.get(i));
                }
            }
        }

        List<UserGroupPO> userGroups = userGroupMapper.selectList(queryWrapper);
        List<Integer> userGroupIds = new ArrayList<>();
        for (UserGroupPO userGroup : userGroups) {
            userGroupIds.add(userGroup.getId());
        }
        return userGroupIds;
    }
}
